import imghdr
from PIL import Image

def is_image(file_path):
    """
    检查文件是否是图片
    """
    return imghdr.what(file_path) is not None

def is_image_corrupted(file_path):
    """
    检查图片文件是否被损坏
    """
    try:
        with Image.open(file_path) as img:
            # 验证图片完整性
            img.verify()  
            # 图片未损坏
            return False  
    except (IOError, SyntaxError):
        # 图片损坏
        return True  
    
def check_image(file_path):
    """
    综合检查文件是否是图片以及是否损坏
    """
    is_img = is_image(file_path)
    if not is_img:
        return False, "提供的文件不是图片文件！"
    is_corrupted = is_image_corrupted(file_path)
    if is_corrupted:
        return False, "提供的图片文件损已坏！"
    return True, "图片文件有效"




if __name__ == "__main__":
    file_path = r'D:\ph-ai\ph_ai_ocr_tmp_file\th_ebbd4de9229f83e067e685a6142673a3'  # 替换为你的图片文件路径
    is_valid, message = check_image(file_path)
    print(message)